package com.sbj.service.impl;

import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapBuilder;
import cn.zhxu.bs.util.MapUtils;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbj.dto.req.OrderTimeReq;
import com.sbj.dto.res.OrderTimeRes;
import com.sbj.dto.utils.Search;
import com.sbj.entity.OrderTime;
import com.sbj.mapper.OrderTimeMapper;
import com.sbj.service.OrderTimeService;
import com.zmh.framework.constants.Constants;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/8/11 09:29
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class OrderTimeServiceImpl extends ServiceImpl<OrderTimeMapper, OrderTime> implements OrderTimeService {

    @Override
    public boolean saveOrUpdate(OrderTime entity) {
        if(entity.getState().equals(Constants.ZERO)){
            LambdaQueryWrapper<OrderTime> eq = Wrappers.lambdaQuery(OrderTime.class).eq(OrderTime::getState, Constants.ONE);
            OrderTime orderTime=new OrderTime();
            orderTime.setState(Constants.ZERO);
            this.update(orderTime,eq);
        }
        return super.saveOrUpdate(entity);
    }

    private final BeanSearcher beanSearcher;

    @Override
    public Page<OrderTimeRes> lists(OrderTimeReq orderTimeReq) {
        Map<String, Object> build = MapUtils.builder().page(orderTimeReq.getPageNum() - 1, orderTimeReq.getPageSize()).build();
        return Search.searchDataList(orderTimeReq.getPageNum(), orderTimeReq.getPageSize(), beanSearcher.search(OrderTimeRes.class,build));
    }

    @Override
    public OrderTimeRes buyTime() {
        MapBuilder builder = MapUtils.builder().field(OrderTimeRes::getDeleted, Constants.ZERO).field(OrderTimeRes::getState, Constants.ZERO);
        return beanSearcher.searchFirst(OrderTimeRes.class,builder.build());
    }
}
